<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use App\User;
use EasyWeChat\MiniProgram\Application;
use Illuminate\Support\Facades\Log;

class WeChatNotify extends BaseModel
{
    protected $table = "t_user_wechat_notifies";

    protected function miniApp()
    {
        return new Application(\config('wechat.mini_program.default'));
    }
    public function notifyConfig()
    {
        $items = \config('wechatnotify');
        return $items['template'][$items['default']];
    }

    /*
     * 购买成功通知:
    物品名称{{keyword1.DATA}}\n
    交易单号{{keyword2.DATA}}\n
    购买价格{{keyword3.DATA}}\n
    购买时间{{keyword4.DATA}}\n
    购买地点{{keyword5.DATA}}\n
    客服电话{{keyword6.DATA}}\n
    订单号{{keyword7.DATA}}\n
    数量{{keyword8.DATA}}\n
     */
    public function buySuccessNotify($order)
    {
        $data = [
            'keyword1' => $order->product_name,
            'keyword2' => $order->payRecord->transaction_id,
            'keyword3' => floatval($order->price).'元',
            'keyword4' => $order->created_at->toDateTimeString(),
            'keyword5' => '线上支付',
            'keyword6' => $this->notifyConfig()['KEFU_TEL'],
            'keyword7' => $order->out_trade_no,
            'keyword8' => $order->quantity,
        ];
        $msg = [
            'touser' => $order->createUser->weixinId,
            'template_id' => $this->notifyConfig()['BUY_SUCCESS'],
            'page' => 'pages/QRcode/index?to=order&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);

    }

    /*
     * 订单发货提醒:
    快递公司{{keyword1.DATA}}\n
    快递单号{{keyword2.DATA}}\n
    发货平台{{keyword3.DATA}}\n
    订单号{{keyword4.DATA}}\n
    发货时间{{keyword5.DATA}}\n
    物品名称{{keyword6.DATA}}\n
     *
     */
    public function orderDelivery($express)
    {
        $data = [
            'keyword1' => $express->carrier->name_cn,
            'keyword2' => $express->tracking_number,
            'keyword3' => $this->notifyConfig()['FAHUO'],
            'keyword4' => $express->out_trade_no,
            'keyword5' => $express->created_at,
            'keyword6' => $express->title,

        ];
        $msg = [
            'touser' => $express->order->getUser->weixinId,
            'template_id' => $this->notifyConfig()['ORDER_DELIVERY'],
            'page' => 'pages/QRcode/index?to=order&id='.$express->order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }

    /*
     * 活动订单发货提醒:
    快递公司{{keyword1.DATA}}\n
    快递单号{{keyword2.DATA}}\n
    发货平台{{keyword3.DATA}}\n
    订单号{{keyword4.DATA}}\n
    发货时间{{keyword5.DATA}}\n
    物品名称{{keyword6.DATA}}\n
     *
     */
    public function activityOrderDelivery($activityOrder)
    {
        $data = [
            'keyword1' => $activityOrder->express_name,
            'keyword2' => $activityOrder->express_number,
            'keyword3' => $this->notifyConfig()['FAHUO'],
            'keyword4' => $activityOrder->out_trade_no,
            'keyword5' => $activityOrder->created_at->toDateTimeString(),
            'keyword6' => $activityOrder->activity_name,

        ];
        $msg = [
            'touser' => $activityOrder->openid,
            'template_id' => $this->notifyConfig()['ORDER_DELIVERY'],
            'page' => 'pages/QRcode/index?to=activity&id='.$activityOrder->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }
    /*
     * 退款通知
    物品名称{{keyword1.DATA}}\n
    订单编号{{keyword2.DATA}}\n
    退款时间{{keyword3.DATA}}\n
    退款原因{{keyword4.DATA}}\n
    退款方式{{keyword5.DATA}}\n
    退款状态{{keyword6.DATA}}\n
    客服电话{{keyword7.DATA}}\n
    退款金额{{keyword8.DATA}}\n
     */
    public function refund($order)
    {
        $data = [
            'keyword1' => $order->product_name,
            'keyword2' => $order->out_trade_no,
            'keyword3' => $order->payRecord->updated_at,
            'keyword4' => $order->payRecord->refund_desc,
            'keyword5' => '原路返回',
            'keyword6' => $order->payRecord->ch_refund_status,
            'keyword7' =>  $this->notifyConfig()['KEFU_TEL'],
            'keyword8' => floatval($order->payRecord->refund_fee).'元',
        ];
        $msg = [
            'touser' => $order->createUser->weixinId,
            'template_id' => $this->notifyConfig()['REFUND'],
            'page' => 'pages/QRcode/index?to=order&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }
    /*
     * 确认收货通知
    商品详情{{keyword1.DATA}}\n
    订单编号{{keyword2.DATA}}\n
    确认收货时间{{keyword3.DATA}}\n
    商家电话{{keyword4.DATA}}\n
    温馨提示{{keyword5.DATA}}\n
     */
    public function confirmReceipt($order)
    {
        $data = [
            'keyword1' => $order->product_name,
            'keyword2' => $order->out_trade_no,
            'keyword3' => $order->finish_time,
            'keyword4' => $this->notifyConfig()['KEFU_TEL'],
            'keyword5' => '您购买的'.$order->product_name.'已确认收获，如果不是您本人签收，请尽快联系商家',
        ];
        $msg = [
            'touser' => $order->getUser->weixinId,
            'template_id' => $this->notifyConfig()['CONFIRM_RECEIPT'],
            'page' => 'pages/QRcode/index?to=order&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }
    /*
     * 卡券到期提醒
    商家名称{{keyword1.DATA}}\n
    卡券类别{{keyword2.DATA}}\n
    失效日期{{keyword3.DATA}}\n
    温馨提示{{keyword4.DATA}}\n
     */
    public function cardExpire($order)
    {
        $d = floor((strtotime($order->expire_time) - time())/86400);

        if ($d<0) return false;
        $data = [
            'keyword1' => $this->notifyConfig()['SHANG_JIA'],
            'keyword2' => '礼品卡',
            'keyword3' => $order->expire_time,
            'keyword4' => '卡券还有'.$d.'天到期，请及时使用！',
        ];
        $msg = [
            'touser' => $order->createUser->weixinId,
            'template_id' => $this->notifyConfig()['CARD_EXPIRE'],
            'page' =>'pages/QRcode/index?to=cardExpire&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }

    /*
     * 礼品卡被领通知
    名称{{keyword1.DATA}}\n
    领用人{{keyword2.DATA}}\n
    领用时间{{keyword3.DATA}}\n
     */

    public function giftReceived($order)
    {
        $data = [
            'keyword1' => $order->product_name,
            'keyword2' => $order->getUser->name?$order->getUser->name:$order->username,
            'keyword3' => $order->get_time,
        ];
        $msg = [
            'touser' => $order->createUser->weixinId,
            'template_id' => $this->notifyConfig()['GIFT_RECEIVED'],
            'page' => 'pages/QRcode/index?to=giftReceived&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }

    /*
     * 试用申请通知
    申请人{{keyword1.DATA}}\n
    试用名称{{keyword2.DATA}}\n
    申请时间{{keyword3.DATA}}\n
    申请状态{{keyword4.DATA}}\n
    备注说明{{keyword5.DATA}}\n
     */
    public function applyPass($order)
    {
        $data = [
            'keyword1' => $order->user->name,
            'keyword2' => $order->activity_name,
            'keyword3' => $order->created_at->toDateTimeString(),
            'keyword4' => $order->apply_status,
            'keyword5' => '感谢您的参与，请及时关注下期活动！',
        ];
        $msg = [
            'touser' => $order->user->weixinId,
            'template_id' => $this->notifyConfig()['TRY_APPLY'],
            'page' => 'pages/QRcode/index?to=activity&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }
    /*
     * 试用报告提交提醒
    试用名称{{keyword1.DATA}}\n
    申请人{{keyword2.DATA}}\n
    申请成功时间{{keyword3.DATA}}\n
    提交截止时间{{keyword4.DATA}}\n
    备注{{keyword5.DATA}}\n
     */
    public function applyFeedback($order)
    {
        $data = [
            'keyword1' => $order->activity_name,
            'keyword2' => $order->user->name,
            'keyword3' => date('Y-m-d',strtotime($order->send_pass_time)),
            'keyword4' => date('Y-m-d',strtotime($order->feedback_deadline)),
            'keyword5' => '请尽快提交报告信息，谢谢！',
        ];
        $msg = [
            'touser' => $order->user->weixinId,
            'template_id' => $this->notifyConfig()['TRY_REPORT_SUBMIT'],
            'page' => 'pages/QRcode/index?to=activity&id='.$order->id,
            'data' => $data
        ];
        return $this->process_send($msg);
    }

    //预发送
    public function process_send($msg)
    {
        $user = User::where('weixinId','=',$msg['touser'])->first();

        if (!$user) return false;

        $data = Helpers::getTempJson('wechat_notify_template',true);
        if (!$data) {
            $data = $this->miniApp()->template_message->getTemplates(0,20);
            Helpers::saveTempJson($data,'wechat_notify_template');
        }
        if (!$data || ($data&&$data['errcode']!=0)) return false;

        $template = false;

        //查找模板
        foreach ($data['list'] as $k=>$v){
            if ($v['template_id'] == $msg['template_id']){
                $template = $v;
                break;
            }
        }

        if ($template) {
            $content = $template['content'];
            foreach ($msg['data'] as $k=>$v){
                $content = str_replace('{{'.$k.'.DATA}}',':'.$v,$content);
            }
            $m = new WeChatNotify();
            $m->title = $template['title'];
            $m->content = $content;
            $m->user_id = $user->id;
            $m->openid = $user->weixinId;
            $m->username = $user->name;
            $m->save();

            return self::send_notify($m,$msg);
        }
        return false;
    }

    //发送模板消息
    public function send_notify($item,$data,$count=1)
    {
        if ($item->state === 0) return false;
        $form = WeChatFromId::getOneFormId($data['touser']);

        if (!$form) {
            $item->state = 41028;
            $item->state_msg = '没有form_id,无法发送消息';
            $item->save();
            return false;
        }

        $data['form_id'] = $form->form_id;

        try{
            if ($resp = $this->miniApp()->template_message->send($data)) {
                //if ($resp = $this->mockSend($count)) {
                $item->state = $resp['errcode'];
                $item->state_msg = $resp['errmsg'];
                $item->send_count = $count;
                $item->save();

                if (!in_array($resp['errcode'],[410028,41028])) {
                    $form->count -=1;
                    $form->save();
                }

                if ($resp['errcode'] == 0) {
                    return true;
                } elseif (in_array($resp['errcode'],[410028,41028])){
                    return self::send_notify($item,$data,$count+1);
                }
            }
        }catch (\Exception $e){
            Log::error($e->getMessage());
        }

        return false;
    }

    protected function mockSend($count)
    {
        if ($count ==1){
            return [
                'errcode' => 410028,
                'errmsg' => 'form_id不正确，或者过期'
            ];
        }else{
            return [
                'errcode' => 0,
                'errmsg' => 'ok'
            ];
        }

    }
}
